package com.siyuanren.gcocp.facade.impl;

import com.alibaba.fastjson.JSON;
import com.siyuanren.gcocp.common.exception.BaseException;
import com.siyuanren.gcocp.common.web.bean.Token;
import com.siyuanren.gcocp.consts.GcocpConsts;
import com.siyuanren.gcocp.consts.RedisConsts;
import com.siyuanren.gcocp.consts.RedisWxConsts;
import com.siyuanren.gcocp.facade.JedisFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Set;


/**
 * Created by   guwr
 * Project_name gcocp-parent
 * Path         com.siyuanren.gcocp.facade.impl.JedisFacadeSingleImpl
 * Date         2017/6/19
 * Time         11:07
 * Description  单一
 */
@Primary
@Component
public class JedisFacadeSingleImpl implements JedisFacade {

    private static Logger logger = LoggerFactory.getLogger(JedisFacadeSingleImpl.class);
    @Autowired
    private JedisPool jedisPool;

    public static void main(String[] args) {

    }

    @Override
    public Set<String> delByPattern(String pattern) {
        logger.info("pattern = [" + pattern + "]");
        Set<String> keys = getByPattern(pattern);
        if (!CollectionUtils.isEmpty(keys)) {
            keys.forEach(this::del);
        }
        return keys;
    }

    @Override
    public Set<String> getByPattern(String pattern) {
        logger.info("pattern = [" + pattern + "]");
        Jedis jedis = null;
        Set<String> getByPattern = null;
        try {
            jedis = getJedis();
            getByPattern = jedis.keys(pattern);
        } catch (Exception e) {
            logger.info("getByPattern is null");
        } finally {
            getColse(jedis);
        }
        return getByPattern;
    }

    @Override
    public Long hset(String key, String field, String value) {
        Jedis jedis = null;
        Long hset = null;
        try {
            jedis = getJedis();
            hset = jedis.hset(key, field, value);
        } catch (Exception e) {
            logger.info("hset is null");
        } finally {
            getColse(jedis);
        }
        return hset;
    }

    @Override
    public String hget(String key, String field) {
        Jedis jedis = null;
        String hget = null;
        try {
            jedis = getJedis();
            hget = jedis.hget(key, field);
        } catch (Exception e) {
            logger.info("hget is null");
        } finally {
            getColse(jedis);
        }
        return hget;
    }

    @Override
    public Long hdel(String key, String field) {
        Jedis jedis = null;
        Long hdel = null;
        try {
            jedis = getJedis();
            hdel = jedis.hdel(key, field);
        } catch (Exception e) {
            logger.info("hdel is null");
        } finally {
            getColse(jedis);
        }
        return hdel;
    }

    @Override
    public Boolean hexists(String key, String field) {
        Jedis jedis = null;
        Boolean hexists = null;
        try {
            jedis = getJedis();
            hexists = jedis.hexists(key, field);
        } catch (Exception e) {
            logger.info("hexists is null");
        } finally {
            getColse(jedis);
        }
        return hexists;
    }

    @Override
    public String setex(String key, int seconds, String value) {
        Jedis jedis = null;
        String setex = null;
        try {
            jedis = getJedis();
            setex = jedis.setex(key, seconds, value);
        } catch (Exception e) {
            logger.info("setex is null");
        } finally {
            getColse(jedis);
        }
        return setex;
    }

    @Override
    public Long setnx(String key, String value) {
        Jedis jedis = null;
        Long setnx = null;
        try {
            jedis = getJedis();
            setnx = jedis.setnx(key, value);
        } catch (Exception e) {
            logger.info("setnx is null");
        } finally {
            getColse(jedis);
        }
        return setnx;
    }

    @Override
    public Long del(String key) {
        Jedis jedis = null;
        Long del = null;
        try {
            jedis = getJedis();
            del = jedis.del(key);
        } catch (Exception e) {
            logger.info("del is null");
        } finally {
            getColse(jedis);
        }
        return del;
    }

    @Override
    public Long zrem(String key, String member) {
        Jedis jedis = null;
        Long zrem = null;
        try {
            jedis = getJedis();
            zrem = jedis.zrem(key, member);
        } catch (Exception e) {
            logger.info("zrem is null");
        } finally {
            getColse(jedis);
        }
        return zrem;
    }

    @Override
    public String get(String key) {
        Jedis jedis = null;
        String get = null;
        try {
            jedis = getJedis();
            get = jedis.get(key);
        } catch (Exception e) {
            logger.info("get is null");
        } finally {
            getColse(jedis);
        }
        return get;
    }

    @Override
    public String set(String key, String value) {
        Jedis jedis = null;
        String set = null;
        try {
            jedis = getJedis();
            set = jedis.set(key, value);
        } catch (Exception e) {
            logger.info("set is null");
        } finally {
            getColse(jedis);
        }
        return set;
    }

    @Override
    public Long sadd(String key, String member) {
        Jedis jedis = null;
        Long sadd = null;
        try {
            jedis = getJedis();
            sadd = jedis.sadd(key, member);
        } catch (Exception e) {
            logger.info("sadd is null");
        } finally {
            getColse(jedis);
        }
        return sadd;
    }

    @Override
    public Boolean sismember(String key, String member) {
        Jedis jedis = null;
        Boolean sismember = null;
        try {
            jedis = getJedis();
            sismember = jedis.sismember(key, member);
        } catch (Exception e) {
            logger.info("sismember is null");
        } finally {
            getColse(jedis);
        }
        return sismember;
    }

    @Override
    public Set<String> zrange(String seatKey, long start, long end) {
        Jedis jedis = null;
        Set<String> zrange = null;
        try {
            jedis = getJedis();
            zrange = jedis.zrange(seatKey, start, end);
        } catch (Exception e) {
            logger.info("zrange is null");
        } finally {
            getColse(jedis);
        }
        return zrange;
    }

    @Override
    public Long zcard(String key) {
        Jedis jedis = null;
        Long zcard = null;
        try {
            jedis = getJedis();
            zcard = jedis.zcard(key);
        } catch (Exception e) {
            logger.info("zcard is null");
        } finally {
            getColse(jedis);
        }
        return zcard;
    }

    @Override
    public Set<String> zrangeByScore(String key, double min, double max) {
        Jedis jedis = null;
        Set<String> zrangeByScore = null;
        try {
            jedis = getJedis();
            zrangeByScore = jedis.zrangeByScore(key, min, max);
        } catch (Exception e) {
            logger.info("zrangeByScore is null");
        } finally {
            getColse(jedis);
        }
        return zrangeByScore;
    }

    @Override
    public void zadd(String key, double score, String member) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.zadd(key, score, member);
        } catch (Exception e) {
            logger.info("zadd is null");
        } finally {
            getColse(jedis);
        }
    }
    @Override
    public Boolean exists(String key) {
        Jedis jedis = null;
        Boolean exists = null;
        try {
            jedis = getJedis();
            exists = jedis.exists(key);
        } catch (Exception e) {
            logger.info("exists is null");
        } finally {
            getColse(jedis);
        }
        return exists;
    }

    @Override
    public Long expire(String key, int seconds) {
            Jedis jedis = null;
            Long expire = 0L;
            try {
                jedis = getJedis();
                expire = jedis.expire(key, seconds);
            } catch (Exception e) {
            logger.info("expire is null");
        } finally {
            getColse(jedis);
        }
        return expire;
    }

    @Override
    public boolean tokenExist(String token) {
        //登录token
//        String tokenKey = RedisConsts.TOKEN_PREFIX + token;
        Boolean exists = exists(token);
        if (exists) {
            expire(token, GcocpConsts.LOGIN_TOKEN_TIME_OUT);
            return true;
        }
        return false;
    }

    @Override
    public Token getByToken(String token) {
        String tokenKey = RedisWxConsts.REDIS_LOGIN_TOKEN_WX + token;
        String loginUser = get(tokenKey);
        Token dto = JSON.parseObject(loginUser, Token.class);
        return dto;
    }

    @Override
    public void logOut(String token) {
        logger.info("logOut,token={}", token);
        del(RedisWxConsts.REDIS_LOGIN_TOKEN_WX + token);
    }

    /**
     * 获取连接
     */
    private Jedis getJedis() {
        try {
            Jedis jedis = jedisPool.getResource();
            if (jedis == null) {
                throw BaseException.REDIS_ERROR;
            }
            return jedis;
        } catch (Exception e) {
            logger.info("getJedis is null");
            return null;
        }
    }

    private void getColse(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}
